let express = require('express');
let router = express.Router();
const nodemailer = require("nodemailer");

// 封装nodemailer对象
let nodeEmail = {
    config: {
        host: "smtp.qq.com",
        port: 587,
        secure: false, // true for 465, false for other ports
        auth: {
            user: "1490814083@qq.com", // generated ethereal user
            pass: "vctsdrzqfdhcjgif" // generated ethereal password
        }
    },
    get transporter() {
        return nodemailer.createTransport(this.config)
    },
    get verifyCode() {
        return Math.random().toString().substring(2, 6);
    }
}

// 写一个验证码接口
router.get('/verify', (req, res, next) => {
    let email = req.query.email;
    let verifyCode = nodeEmail.verifyCode;
    //验证码和邮箱存入session
    req.session.email = email;
    req.session.verifyCode = verifyCode;

    let options = {
        from: "bidding-system<1490814083@qq.com>", // sender address
        to: email, // list of receivers
        subject: "邮箱验证码", // Subject line
        text: `验证码：${verifyCode}`, // plain text body
    };
    nodeEmail.transporter.sendMail(options).then(result => {
        res.send({
            msg: "验证码发送成功",
            status: 0,
            verifyCode: verifyCode
        })
    }).catch(err => {
        console.log(`验证码发送失败${err}`);
        res.send({
            msg: "验证码发送失败",
            status: -1
        })
    });
});
